package com.upup.train_management.controller;

import com.upup.train_management.entity.User;
import com.upup.train_management.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/users")
public class UserController {

    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping
    public ResponseEntity<List<User>> getAllUsers() {
        // 只有管理员能查看所有用户
        User currentUser = getCurrentUser();
        if (currentUser != null && "ADMIN".equals(currentUser.getUserRole())) {
            return ResponseEntity.ok(userService.getAllUsers());
        }
        return ResponseEntity.status(403).build();
    }

    @GetMapping("/{id}")
    public ResponseEntity<User> getUserById(@PathVariable Long id) {
        User user = userService.getUserById(id);
        if (user == null) {
            return ResponseEntity.notFound().build();
        }

        // 验证用户只能查看自己的信息
        User currentUser = getCurrentUser();
        if (currentUser == null || (!isAdmin(currentUser) && !user.getId().equals(currentUser.getId()))) {
            return ResponseEntity.status(403).build();
        }

        return ResponseEntity.ok(user);
    }

    @GetMapping("/current")
    public ResponseEntity<User> getCurrentUserInfo() {
        User currentUser = getCurrentUser();
        if (currentUser == null) {
            return ResponseEntity.status(401).build();
        }

        return ResponseEntity.ok(currentUser);
    }

    @PostMapping("/register")
    public ResponseEntity<?> registerUser(@RequestBody User user) {
        // 检查用户名是否已存在
        if (userService.isUsernameExists(user.getUsername())) {
            return ResponseEntity.badRequest().body("用户名已存在");
        }

        // 检查邮箱是否已存在
        if (user.getEmail() != null && userService.isEmailExists(user.getEmail())) {
            return ResponseEntity.badRequest().body("邮箱已被注册");
        }

        // 检查手机号是否已存在
        if (user.getPhone() != null && userService.isPhoneExists(user.getPhone())) {
            return ResponseEntity.badRequest().body("手机号已被注册");
        }

        User registeredUser = userService.registerUser(user);
        return ResponseEntity.ok(registeredUser);
    }

    @PutMapping("/{id}")
    public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User user) {
        User existingUser = userService.getUserById(id);
        if (existingUser == null) {
            return ResponseEntity.notFound().build();
        }

        // 验证用户只能更新自己的信息
        User currentUser = getCurrentUser();
        if (currentUser == null || (!isAdmin(currentUser) && !existingUser.getId().equals(currentUser.getId()))) {
            return ResponseEntity.status(403).build();
        }

        user.setId(id);
        return ResponseEntity.ok(userService.updateUser(user));
    }

    @PutMapping("/{id}/change-password")
    public ResponseEntity<?> changePassword(
            @PathVariable Long id,
            @RequestBody Map<String, String> passwords) {
        // 验证用户只能更新自己的密码
        User currentUser = getCurrentUser();
        if (currentUser == null || (!isAdmin(currentUser) && !id.equals(currentUser.getId()))) {
            return ResponseEntity.status(403).build();
        }

        String oldPassword = passwords.get("oldPassword");
        String newPassword = passwords.get("newPassword");

        if (oldPassword == null || newPassword == null) {
            return ResponseEntity.badRequest().body("密码参数不完整");
        }

        boolean changed = userService.changePassword(id, oldPassword, newPassword);
        if (changed) {
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.badRequest().body("原密码不正确");
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
        User user = userService.getUserById(id);
        if (user == null) {
            return ResponseEntity.notFound().build();
        }

        // 验证是否为管理员
        User currentUser = getCurrentUser();
        if (currentUser == null || !isAdmin(currentUser)) {
            return ResponseEntity.status(403).build();
        }

        boolean deleted = userService.deleteUser(id);
        if (deleted) {
            return ResponseEntity.noContent().build();
        } else {
            return ResponseEntity.status(400).build();
        }
    }

    private User getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if (authentication == null || !authentication.isAuthenticated()) {
            return null; // Not authenticated at all
        }

        String currentPrincipalName = authentication.getName();
        // Explicitly treat "anonymousUser" as not logged in for our API's purpose
        if ("anonymousUser".equals(currentPrincipalName)) {
            return null;
        }

        // At this point, user is authenticated and not the standard "anonymousUser"
        User user = userService.getUserByUsername(currentPrincipalName);

        // If user not found in DB, or essential fields like username/role are missing,
        // treat as invalid/not properly logged in for the context of this API.
        if (user == null || user.getUsername() == null || user.getUsername().isEmpty() || user.getUserRole() == null || user.getUserRole().isEmpty()) {
            return null;
        }
        
        return user;
    }

    private boolean isAdmin(User user) {
        return "ADMIN".equals(user.getUserRole());
    }
}